<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use think\Db;
use app\mill\model\Give as GiveModel;

/**
 * 面积表模型
 */
class Archives extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_order_archives';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 定义表格字段
    public static $layui_fields = [
        [
            'field'     =>  'sort',
            'title'     =>  '序号',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'page',
            'title'     =>  '图纸页码',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'model_sn',
            'title'     =>  '铝板编号',
            'width'     =>  '300',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'number',
            'title'     =>  '数量',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'cutting',
            'title'     =>  '开料',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'size',
            'title'     =>  '尺寸',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'one_area',
            'title'     =>  '单件面积(M²)',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'row_area',
            'title'     =>  '合计面积(M²)',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'long',
            'title'     =>  'L(MM)',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'high',
            'title'     =>  'H(MM)',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'color',
            'title'     =>  '颜色',
            'width'     =>  '400',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'thickness',
            'title'     =>  '板厚(MM)',
            'align'     =>  'center',
            'width'     =>  '70',
            'escape'    =>  false,
        ],
        [
            'field'     =>  'model',
            'title'     =>  '铝板版型',
            'width'     =>  '300',
            'align'     =>  'center',
            'escape'    =>  false,
        ],
    ];

    // 定义已发货表格字段
    public static $fields4 = [
        'sort'          =>  '序号',
        'model_sn'      =>  '板号[5:1]',
        'long'          =>  'L',
        'high'          =>  'H',
        'one_area'      =>  '单件面积/M²',
        'number'        =>  '数量/件',
        'row_area'      =>  '总面积/M²',
        'thickness'     =>  '板厚',
        'model'         =>  '版型',
        'color'         =>  '颜色',
        'slot'          =>  '刨槽/M',
        'slot_price'    =>  '刨槽/单价',
        'weld'          =>  '焊缝/M',
        'weld_price'    =>  '焊缝/单价',
        'price'         =>  '单价/元',
        'price_sum'     =>  '合价/元',
        'archives_id'   =>  '',
        'order_id'      =>  '',
        'archives_sn'   =>  '',
        'batch'         =>  '',
    ];

    /**
     * 获取面积表信息
     * @param null $id order_id
     * @param string $fields field
     * @param string $order order
     * @param string $group group
     * @param array $join join
     * @param array $where where
     * @param string $table table
     * @return array|\PDOStatement|string|\think\Collection
     */
    public static function getList($id = null,$fields = '',$order = "CONVERT (REPLACE(a.sort,'#','999999'),signed) ASC",$group = '',$join = [],$where = [],$table = 'mill_order_archives'){
        if (!$id && empty($where))return [];
        if(empty($order))$order = "CONVERT (REPLACE(a.sort,'#','999999'),signed) ASC";

        if(empty($where))$where[] = ['a.order_id','=',$id];

        $layui_fields = [];
        foreach (self::$layui_fields as $lhv){
            $layui_fields[$lhv['field']] = $lhv['title'];
        }
        $fields = $fields?$fields:array_keys($layui_fields);

        $lists = Db::name($table)->alias('a')->field($fields)->join($join)->where($where)->group($group)->orderRaw($order)->select();

        return $lists;

    }

    // 统计工程面积表信息
    public static function getOneStat($val = null,$field = 'order_id',$condition = 'eq',$map = [],$time = [],$status = 0){

        GiveModel::init();

        //获取生产状态
        $give_status = GiveModel::$give_status_search;
        //获取最后一个生产状态
        $last_give_status = GiveModel::$last_give_status;

        $new_field = $field == 'archives_id'?'id':$field;
        $where[] = ['a.'.$new_field,$condition,$val];
        $where_give[] = ['l.'.$field,$condition,$val];
        if(!empty($map))$where_give = $where = $map;
        if(empty($time[0]))$time[0] = 0;
        if(empty($time[1]))$time[1] = time();
        $data = Db::name('mill_order_archives')->alias('a')->field('group_concat(DISTINCT order_id) as order_ids,sum(a.number) as number_sum,sum(a.row_area) as area_sum')->where($where)->find();
        $data["area_sum"] = round($data["area_sum"],4);

        //拆分工程批次，根据工程批次各自的工艺统计信息
        $give_sort_arr = Db::name('mill_order')->where([['id','in',$data['order_ids']]])->column('give_sort','id');

        //仅获取对应状态的统计信息
        if(!empty($status)) {
            //只有一个工程批次
            if (count($give_sort_arr) <= 1) {
                //没有这个工艺，则直接返回
                if (!in_array($status, explode(',', reset($give_sort_arr)))) {
                    $data['status_sum'] = $data['status_area_sum'] = $data["status_no_sum"] = $data["status_area_no_sum"] = '<font class="text-danger">无此工艺</font>';
                } else {
                    $status_arr = Db::name('mill_order_archives_give_log')->alias('l')->field('count(l.id) as status_sum,sum(l.one_area) as status_area_sum')->where($where_give)->where(['l.status' => $status])->find();
                    $data = array_merge($data, $status_arr);
                    $data["status_area_sum"] = round($data["status_area_sum"], 4);
                    $data["status_no_sum"] = $data["number_sum"] - $data["status_sum"];
                    $data["status_area_no_sum"] = $data['area_sum'] - $data["status_area_sum"];
                }

            }
            //多个工程批次
            else {
                if (!isset($data["status_sum"])) $data["status_sum"] = 0;
                if (!isset($data["status_area_sum"])) $data["status_area_sum"] = 0;

                //遍历工程批次
                foreach ($give_sort_arr as $order_id => $give_sort) {
                    $give_sort = explode(',', $give_sort);

                    //该工程批次，没有这个工艺时，则默认取面积表的数量和面积
                    if (!in_array($status, $give_sort)) {
                        $status_arr = Db::name('mill_order_archives')->alias('a')->field('sum(a.number) as status_sum,sum(a.row_area) as status_area_sum')->where($where)->where(['order_id' => $order_id])->find();
                    } else {
                        $status_arr = Db::name('mill_order_archives_give_log')->alias('l')->field('count(l.id) as status_sum,sum(l.one_area) as status_area_sum')->where($where_give)->where(['l.status' => $status])->where(['l.order_id' => $order_id])->find();
                    }

                    //累加扫码记录的数量和面积
                    $data["status_sum"] += $status_arr['status_sum'];
                    $data["status_area_sum"] += round($status_arr["status_area_sum"], 4);

                }
                //所有工程的总数量和面积 - 累加扫码记录的数量和面积 = 未完成的数量和面积
                $data["status_no_sum"] = $data["number_sum"] - $data["status_sum"];
                $data["status_area_no_sum"] = $data['area_sum'] - $data["status_area_sum"];

            }

        }
        //仅获取所有生产状态的统计信息
        else{

            foreach ($give_status as $gk=>$gs){
                if($gk <= 0)continue;

                //只有一个工程批次
                if (count($give_sort_arr) <= 1) {
                    //没有这个工艺，则直接返回
                    if (!in_array($gk, explode(',', reset($give_sort_arr)))) {
                        $data["status{$gk}_sum"] = $data["status{$gk}_area_sum"] = $data["status{$gk}_no_sum"] = $data["status{$gk}_area_no_sum"] = '<font class="text-danger">无此工艺</font>';
                    } else {
                        $status_arr = Db::name('mill_order_archives_give_log')->alias('l')->field("count(l.id) as status{$gk}_sum,sum(l.one_area) as status{$gk}_area_sum")->where($where_give)->where(['l.status'=>$gk])->find();
                        $data = array_merge($data,$status_arr);
                        $data["status{$gk}_area_sum"] = round($data["status{$gk}_area_sum"],4);
                        $data["status{$gk}_no_sum"] = $data["number_sum"]-$data["status{$gk}_sum"];
                        $data["status{$gk}_area_no_sum"] = $data['area_sum']-$data["status{$gk}_area_sum"];
                    }

                }
                //多个工程批次
                else{
                    if (!isset($data["status{$gk}_sum"])) $data["status{$gk}_sum"] = 0;
                    if (!isset($data["status{$gk}_area_sum"])) $data["status{$gk}_area_sum"] = 0;

                    //遍历工程批次
                    foreach ($give_sort_arr as $order_id => $give_sort) {
                        $give_sort = explode(',', $give_sort);

                        //该工程批次，没有这个工艺时，则默认取面积表的数量和面积
                        if (!in_array($status, $give_sort)) {
                            $status_arr = Db::name('mill_order_archives')->alias('a')->field("sum(a.number) as status{$gk}_sum,sum(a.row_area) as status{$gk}_area_sum")->where($where)->where(['order_id' => $order_id])->find();
                        } else {
                            $status_arr = Db::name('mill_order_archives_give_log')->alias('l')->field("count(l.id) as status{$gk}_sum,sum(l.one_area) as status{$gk}_area_sum")->where($where_give)->where(['l.status'=>$gk])->find();
                        }

                        //累加扫码记录的数量和面积
                        $data["status{$gk}_sum"] += $status_arr["status{$gk}_sum"];
                        $data["status{$gk}_area_sum"] += round($status_arr["status{$gk}_area_sum"], 4);

                    }
                    //所有工程的总数量和面积 - 累加扫码记录的数量和面积 = 未完成的数量和面积
                    $data["status{$gk}_no_sum"] = $data["number_sum"] - $data["status{$gk}_sum"];
                    $data["status{$gk}_area_no_sum"] = $data['area_sum'] - $data["status{$gk}_area_sum"];

                    //已完成生产的统计信息
                    if($gk == $last_give_status){
                        $data['number_ok_sum'] = $data["status{$gk}_sum"];
                        $data['number_no_sum'] = $data['number_sum']-$data['number_ok_sum'];

                        $data['area_ok_sum'] = $data["status{$gk}_area_sum"];
                        $data['area_no_sum'] = $data['area_sum']-$data['area_ok_sum'];
                    }

                }

            }



        }



        return $data;
    }

    // 插入产品明细
    public static function checkGive($id=null,$archives_id=null){
        $config = new ConfigModel();

        $where = $where2 = ['order_id'=>$id];
        if(!empty($archives_id)){
            $where = ['archives_id'=>$archives_id];
            $where2 = ['id'=>$archives_id];
        }
        $count = Db::name('mill_order_archives_give')->where($where)->count();

        if(empty($count)){

            $last_give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();

            if(empty($last_give)){
                //当天生产批次配置
                $mill_date_batch = $config->getConfig('mill_date_batch');
                //如果不是当天生产批次，则重置
                if($mill_date_batch['date']!=date('Ymd')){
                    $mill_date_batch['date'] = date('Ymd');
                    $mill_date_batch['batch'] = 0;
                }
                $mill_date_batch['batch'] += 1;
                $mill_date_batch['sort'] = 1;
            }
            else{
                $mill_date_batch['date'] = $last_give['give_date'];
                $mill_date_batch['batch'] = $last_give['batch'];
                $mill_date_batch['sort'] = $last_give['sort']+1;
            }

            //当天日期
            $date = $mill_date_batch['date'];
            //当前批次
            $batch = $mill_date_batch['batch'];
            //当前序号，从1开始
            $sort = $mill_date_batch['sort'];

            $order = Db::name('mill_order')->where('id='.$id)->find();
            $list = self::getList(null,'id,order_id,order_pid,sort,number,sort','','',[],$where2,'mill_order_archives');
            $add_arr = [];
            foreach ($list as $v){

                if($v['number'] >= 1){
                    for ($i=1;$i<=$v['number'];$i++){
                        $add = [
                            'order_id'      =>  $v['order_id'],
                            'order_pid'     =>  $v['order_pid'],
                            'archives_id'   =>  $v['id'],
                            'archives_sn'   =>  $order['archives_sn'],
                            'number'        =>  1,
                            'counter'       =>  $i,
                            'give_date'     =>  $date,
                            'batch'         =>  $batch,
                            'sort'          =>  $sort,
                            'give_sn'       =>  GiveModel::giveSn($date,$batch,$sort),
                        ];
                        $add_arr[] = $add;

                        $sort++;
                    }
                }
            }

            //2000条数据为一批次
            $add_arr_i = intval($sort/2000)+1;
            $add_arr_arr = array_chunk($add_arr, $add_arr_i);
            //分批次插入
            foreach ($add_arr_arr as $varr){
                Db::name('mill_order_archives_give')->insertAll($varr);
            }

            //更新当天生产批次配置
            if(empty($archives_id))ConfigModel::where('name', 'mill_date_batch')->update(['value' => "date:{$date}\r\nbatch:{$batch}"]);
        }

        return true;
    }

    // 检查更新产品状态
    public static function checkStatus($give = [],$give_sort = ''){
        $id = $give['archives_id'];
        $status = $give['status'];
        if($give['status']>0){
            $count = Db::name('mill_order_archives_give_log')->where(['archives_id'=>$id])->where('status='.$status)->count('id');
            if($count >= $give['archives_number']){

                Db::name('mill_order_archives')->where(['id'=>$id])->update(['status'=>$status]);

                $give_sort = explode(',',$give_sort);
                array_pop($give_sort);//删除最后一个生产状态，即发货状态
                $status_end = array_pop($give_sort);//最后一个生产状态，即发货状态

                //更新工程生产周期
                if($status == $status_end){
                    $give_pro_min = Db::name('mill_order_archives_give_log')->where(['order_id'=>$give['order_id']])->order('status_time asc')->value('status_time');
                    $give_pro_max = Db::name('mill_order_archives_give_log')->where(['order_id'=>$give['order_id'],'status'=>$status_end])->order('status_time desc')->value('status_time');
                    $give_pro = ceil(($give_pro_max/86400)-($give_pro_min/86400));
                    Db::name('mill_order')->where(['id'=>$give['order_id']])->update(['give_pro'=>$give_pro]);
                }

            }

            //更新工程产品状态
            $give_status = Db::name('mill_order_archives_give')->where(['order_id'=>$give['order_id']])->order('status desc')->value('status');

            Db::name('mill_order')->where(['id'=>$give['order_id']])->update(['give_status'=>$give_status]);
        }
    }
}
